package org.achievement.system.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.achievement.system.common.RequestResult;
import org.achievement.system.common.annotations.InterfaceAuth;
import org.achievement.system.common.enums.AuthEnum;
import org.achievement.system.common.exception.ServiceException;
import org.achievement.system.dao.CourseDao;
import org.achievement.system.dao.RoleDao;
import org.achievement.system.dao.UserDao;
import org.achievement.system.pojo.entity.Course;
import org.achievement.system.pojo.entity.Role;
import org.achievement.system.pojo.entity.User;
import org.achievement.system.pojo.form.CourseForm;
import org.achievement.system.service.CourseService;

import org.achievement.system.pojo.vo.CourseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

import static org.achievement.system.controller.CommonController.commonSetting;

/**
 * 课程
 */
@RestController
@RequestMapping("/course")
public class CourseController {

    @Autowired
    private CourseService courseService;
    @Autowired
    private CourseDao courseDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private RoleDao roleDao;

    /**
     * 页面
     *
     * @param modelAndView
     * @return
     */
    @InterfaceAuth({AuthEnum.ADMIN, AuthEnum.TEACHER})
    @RequestMapping()
    public ModelAndView index(ModelAndView modelAndView) {
        modelAndView.setViewName("course");
        commonSetting(modelAndView);
        return modelAndView;
    }

    /**
     * 全部数据
     *
     * @return
     */
    @InterfaceAuth({AuthEnum.ADMIN, AuthEnum.TEACHER, AuthEnum.STUDENT})
    @RequestMapping("/allData")
    public RequestResult allData() {
        CourseForm courseForm = new CourseForm();
        courseForm.setMakePage(false);
        RequestResult result = courseService.list(courseForm);
        return result;
    }

    /**
     * 查询
     *
     * @param courseForm
     * @return
     */
    @InterfaceAuth({AuthEnum.ADMIN, AuthEnum.TEACHER, AuthEnum.STUDENT})
    @RequestMapping("/list")
    public RequestResult list(HttpServletRequest request, @RequestBody CourseForm courseForm) {
        // 判断权限，老师只能看到自己的课程
        String username = (String) request.getSession().getAttribute("username");
        User user = userDao.selectOne(new QueryWrapper<User>().eq("username", username));
        Role role = roleDao.selectOne(new QueryWrapper<Role>().eq("id", user.getRoleId()));
        if ("教师".equals(role.getName())) {
            courseForm.setTeacherId(user.getId());
        }
        RequestResult result = courseService.list(courseForm);
        return result;
    }

    /**
     * 增加
     *
     * @param course
     * @return
     */
    @InterfaceAuth({AuthEnum.ADMIN, AuthEnum.TEACHER})
    @RequestMapping("/add")
    public RequestResult add(HttpServletRequest request, @RequestBody Course course) {
        if (course == null) {
            throw new ServiceException("不能提交空数据！");
        }
        if (StrUtil.isBlank(course.getCourseName())) {
            throw new ServiceException("课程名称不能为空！");
        }
        if (course.getTeacherId() == null) {
            throw new ServiceException("教师名称不能为空！");
        }
        String username = (String) request.getSession().getAttribute("username");
        User user = userDao.selectOne(new QueryWrapper<User>().eq("username", username));
        if (user.getId() != course.getTeacherId()) {
            throw new ServiceException("只能添加自己的课程！");
        }
        CourseForm courseForm = new CourseForm();
        courseForm.setCourseName(course.getCourseName());
        courseForm.setTeacherId(course.getTeacherId());
        courseForm.setOffset(0);
        List<CourseVo> list = courseDao.list(courseForm);
        if (list != null && list.size() > 0) {
            for (CourseVo vo : list) {
                if (course.getCourseName().equals(vo.getCourseName())) {
                    throw new ServiceException("请勿重复录入课程！");
                }
            }
        }
        boolean save = courseService.save(course);
        if (! save) {
            throw new ServiceException("保存失败！");
        }
        return RequestResult.success("提交成功！");
    }

    /**
     * 修改
     *
     * @param course
     * @return
     */
    @InterfaceAuth({AuthEnum.ADMIN, AuthEnum.TEACHER})
    @RequestMapping("/edit")
    public RequestResult edit(HttpServletRequest request,@RequestBody Course course) {
        if (course == null) {
            throw new ServiceException("不能提交空数据！");
        }
        if (StrUtil.isBlank(course.getCourseName())) {
            throw new ServiceException("课程名称不能为空！");
        }
        if (course.getTeacherId() == null) {
            throw new ServiceException("教师名称不能为空！");
        }
        String username = (String) request.getSession().getAttribute("username");
        User user = userDao.selectOne(new QueryWrapper<User>().eq("username", username));
        if (user.getId() != course.getTeacherId()) {
            throw new ServiceException("只能修改自己的课程！");
        }
        CourseForm courseForm = new CourseForm();
        courseForm.setCourseName(course.getCourseName());
        courseForm.setTeacherId(course.getTeacherId());
        courseForm.setOffset(0);
        List<CourseVo> list = courseDao.list(courseForm);
        if (list != null && list.size() > 0) {
            for (CourseVo vo : list) {
                if (course.getCourseName().equals(vo.getCourseName())) {
                    throw new ServiceException("有重复课程！");
                }
            }
        }
        boolean save = courseService.updateById(course);
        if (! save) {
            throw new ServiceException("保存失败！");
        }
        return RequestResult.success("提交成功！");
    }

    /**
     * 删除
     *
     * @param ids
     * @return
     */
    @InterfaceAuth({AuthEnum.ADMIN, AuthEnum.TEACHER})
    @RequestMapping("/delete")
    public RequestResult delete(@RequestBody List<Integer> ids) {
        if (ids == null || ids.isEmpty()) {
            throw new ServiceException("请先选择！");
        }
        boolean removed = courseService.removeBatchByIds(ids);
        if ( ! removed) {
            throw new ServiceException("删除失败！");
        }
        return RequestResult.success("删除成功！");
    }


}